package com.yang.frost.blueberry.quartz.service.impl;

import com.yang.frost.blueberry.quartz.entity.JobAndTrigger;
import com.yang.frost.blueberry.quartz.entity.form.JobForm;
import com.yang.frost.blueberry.quartz.mapper.JobMapper;
import com.yang.frost.blueberry.quartz.service.JobService;
import com.yang.frost.blueberry.quartz.util.JobUtil;
import com.yang.frost.blueberry.util.ApiResult;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 10296
 * @date 2021/1/20
 * @Description:
 */
@Service
public class JobServiceImpl implements JobService {

    private Logger logger = LoggerFactory.getLogger(JobServiceImpl.class);

    @Autowired
    private Scheduler scheduler;
    @Autowired
    private JobMapper jobMapper;


    @Override
    public void addJob(JobForm jobForm) throws Exception {
        //启动调度器
        scheduler.start();
        //构建Job信息
        JobDetail jobDetail = JobBuilder.newJob(JobUtil.getClass(jobForm.getJobClassName()).getClass())
                .withIdentity(jobForm.getJobClassName(), jobForm.getJobGroupName())
                .build();
        //Cron表达式调度构建起(即任务执行的时间)
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(jobForm.getCronExpression());

        //根据Cron表达式构建一个Trigger
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(jobForm.getJobClassName(), jobForm.getJobGroupName())
                .withSchedule(scheduleBuilder).build();
        try {
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            logger.error("【定时任务】创建失败！", e);
            e.printStackTrace();

        }

    }

    /**
     * 删除定时任务
     *
     * @param jobForm 表单参数
     * @throws Exception 异常
     */
    @Override
    public void deleteJob(JobForm jobForm) throws Exception {
        scheduler.pauseTrigger(TriggerKey.triggerKey(jobForm.getJobClassName(), jobForm.getJobGroupName()));
        scheduler.unscheduleJob(TriggerKey.triggerKey(jobForm.getJobClassName(), jobForm.getJobGroupName()));
        scheduler.deleteJob(JobKey.jobKey(jobForm.getJobClassName(), jobForm.getJobGroupName()));

    }

    /**
     * 暂停定时任务
     *
     * @param jobForm 表单参数
     * @throws SchedulerException 异常
     */
    @Override
    public void pauseJob(JobForm jobForm) throws SchedulerException {
        scheduler.pauseJob(JobKey.jobKey(jobForm.getJobClassName(), jobForm.getJobGroupName()));

    }

    /**
     * 恢复定时任务
     *
     * @param jobForm 表单参数
     * @throws SchedulerException 异常
     */
    @Override
    public void resumeJob(JobForm jobForm) throws SchedulerException {
        scheduler.resumeJob(JobKey.jobKey(jobForm.getJobClassName(), jobForm.getJobGroupName()));

    }

    /**
     * 重新配置定时任务
     *
     * @param jobForm 表单参数
     * @throws Exception 异常
     */
    @Override
    public void cronJob(JobForm jobForm) throws Exception {

        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(jobForm.getJobClassName(), jobForm.getJobGroupName());
            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(jobForm.getCronExpression());

            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            //根据cron表达式构建一个Trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

            scheduler.rescheduleJob(triggerKey, trigger);
        } catch (SchedulerException e) {
            logger.error("【定时任务】更新失败！", e);
            e.printStackTrace();

        }


    }

    @Override
    public ApiResult list(Map<String, Object> paramsMap) {
        Map<String, Object> resultMap = new HashMap<>();
        List<JobAndTrigger> list = jobMapper.list(paramsMap);

        return ApiResult.ok(list);
    }
}
